package com.test.demoweb.service;

import com.test.demoweb.dao.UserRepository;
import com.test.demoweb.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class UserService {

    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public Mono<User> save(User user) {
        return userRepository.save(user)
                .onErrorResume(e -> userRepository.findByUsername(user.getUsername())
                        .flatMap(originalUser -> {
                            user.setId(originalUser.getId());
                            return userRepository.save(user);
                        }));
    }

    public Mono<Long> deleteByUsername(String username) {
        return userRepository.deleteByUsername(username);
    }

    public Flux<User> findAllByUsername(String username) {
        return userRepository.findAllByUsername(username);
    }

    public Mono<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public Flux<User> findAll() {
        return userRepository.findAll();
    }

    public Mono<Long> countUser() {
        return userRepository.count();
    }
}
